package dev.kelvin.patientservice.service;

import dev.kelvin.patientservice.dto.PatientRequestDTO;
import dev.kelvin.patientservice.dto.PatientResponseDTO;
import dev.kelvin.patientservice.exception.EmalAlreadyExistsException;
import dev.kelvin.patientservice.exception.PatientNotFoundException;
import dev.kelvin.patientservice.mapper.PatientMapper;
import dev.kelvin.patientservice.model.Patient;
import dev.kelvin.patientservice.repository.PatientRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;
import java.util.UUID;

@Service
public class PatientService {

    private PatientRepository patientRepository;

    public PatientService(PatientRepository patientRepository) {
        this.patientRepository = patientRepository;
    }

    public List<PatientResponseDTO> getAllPatients() {
        List<Patient> patients = patientRepository.findAll();
        List<PatientResponseDTO> patientResponseDTOs = patients.stream()
                .map(PatientMapper::toDTO).toList();
        return patientResponseDTOs;
    }

    public PatientResponseDTO createPatient(PatientRequestDTO patientRequestDTO) {
        if (patientRepository.existsByEmail(patientRequestDTO.getEmail())) {
            throw new EmalAlreadyExistsException("Please Use a Different Email" + patientRequestDTO.getEmail());
        }
        Patient patient = patientRepository.save(PatientMapper.toModel(patientRequestDTO));
        return PatientMapper.toDTO(patient);
    }

    public PatientResponseDTO updatePatient(UUID id, PatientRequestDTO patientRequestDTO) {
        Patient patient = patientRepository.findById(id)
                .orElseThrow(()->new PatientNotFoundException("Patient Not Found with ID: "+id));

        if (patientRepository.existsByEmailAndIdNot(patientRequestDTO.getEmail(),id)) {
            throw new EmalAlreadyExistsException("Please Use a Different Email" + patientRequestDTO.getEmail());
        }
        BeanUtils.copyProperties(patientRequestDTO, patient);
        patient.setDateOfBirth(LocalDate.parse(patientRequestDTO.getDateOfBirth()));
        Patient updatedPatient = patientRepository.save(patient);
        return PatientMapper.toDTO(updatedPatient);

    }

    public void deletePatient(UUID id) {
        patientRepository.deleteById(id);
    }
}
